掃描藍芽裝置:
var fs = require("fs");
var noble = require('../node_modules/noble/index.js');
var deviceList = {};
var scanResult = {};
noble.on('discover', function (peripheral) {
if (peripheral.advertisement.localName !== 'device_name') return;
scanResult[peripheral.address] = deviceList[peripheral.address]||"";
});
noble.on('stateChange', function (state) {
if (state === 'poweredOn') {
noble.startScanning([],true);
deviceList = JSON.parse(fs.readFileSync(__dirname+"/../data/"+"deviceList.json"));
} else {
noble.stopScanning();
};
setTimeout(() => {
noble.stopScanning();
}, 5000);
setTimeout(() => {
console.log(JSON.stringify(scanResult));
process.exit(0);
}, 6000);
});
點燈機制
var noble = require('../node_modules/noble/index.js');
var get_device=false;
console.log(process.argv[2]);
noble.on('discover', function (peripheral) {
if ((peripheral.address === process.argv[2]) && (get_device===false)) {
console.log("device got!!");
get_device=true;
noble.stopScanning();
peripheral.connect(err => {
peripheral.discoverServices(["fff0"], (err, service) => {
service[0].discoverCharacteristics(['fff1'], (err, char) => {
if (err) console.log(err); else console.log("connected!");
var buff = new Buffer(20);
buff[0] = 8;
char[0].write(buff);
console.log(`${process.argv[2]} LED ON`);
setTimeout(() => {
buff[0] = 9;
char[0].write(buff,true, err => {
console.log(`${process.argv[2]} LED OFF`);
setTimeout(()=>{
peripheral.disconnect(()=>{
console.log("disconnect");
setTimeout(()=>{
process.exit(0);
},1000);
});
},1000);
});
}, 2000);
});
});
});
}
});
noble.on('stateChange', function (state) {
if (state === 'poweredOn') {
noble.startScanning([],true);
setTimeout(() => {
process.exit(0);
}, 10000);
} else {
noble.stopScanning();
};
});